<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" name="viewport">
    <title>多人聊天室</title>
    <link rel="stylesheet" type="text/css" href="stylesheets/chat.css" />
    <!--[if lt IE 8]><script src="./json3.min.js"></script><![endif]-->
    <script type="text/javascript" src="/javascripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/javascripts/socket.io.js"></script>
    <script type="text/javascript" src="/javascripts/layer/layer.js"></script>
    <link rel="stylesheet" href="stylesheets/bootstrap.min.css" media="screen">
</head>
<body>
<div class="container" id="login" style="width: 500px">
    <form class="col-sm-offset-4 col-sm-4 form-horizontal" role="form" method="post" onsubmit="return false" style="width: 400px;margin-left: 35px;">
        <fieldset>
            <legend></legend>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <p class="tc">请先登录</p>
                </div>
                <div class="panel-body m15">
                    <div class="form-group">
                        <div class="input-group">
                        <span class="input-group-addon">
                        <span class="glyphicon glyphicon-user"></span>
                        </span>
                            <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                        <span class="input-group-addon">
                        <span class="glyphicon glyphicon-lock"></span>
                        </span>
                            <input type="text" class="form-control" id="password" name="password" placeholder="请输入密码" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary btn-block" id="login" onclick="userlogin()">登录</button>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
</div>
<div id="chatbox">
    <div style="background:#3d3d3d;height: 28px; width: 100%;font-size:12px;">
        <div style="line-height: 28px;color:#fff;">
            <span style="text-align:left;margin-left:10px;">Websocket多人聊天室</span>
                    <span style="float:right; margin-right:10px;"><span id="showusername"></span> |
					<a href="javascript:;" onclick="exit()" style="color:#fff;">退出</a></span>
        </div>
    </div>
    <div id="doc">
        <div id="chat">
            <div id="message" class="message clear">
                <div id="onlineuser" style="  background-color:#888888;  width: 30%;float: left;">
                    <div class="fir">好友在线：<label id="countUser"></label>人</div>
                   <div class="fir" id="fir">
                   </div>
                </div>
                 <div  style="background:#ffffff; font-size:12px;width: 646px;float: left; color:#666;overflow: auto;">
                     <div style="margin-left: 5px; height:646px;color:#666;overflow: auto;"  id="onlinecount">

                     </div>
                 </div>
            </div>
            <div class="input-box">
                <div class="input" style=" margin-left: 30%;  width: 600px;">
                    <input type="text" class="text" maxlength="110" placeholder="请输入聊天内容，按Ctrl提交" id="content" name="content">
                    <input type="button" class="button" id="mjr_send" onclick="submit()" value="提交">
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" id="Send" >
<script type="text/javascript">
    $(function(){
        document.onkeydown = function(e){
            var ev = document.all ? window.event : e;
            if(ev.keyCode==13) {
                submit();
            }
        }
       $("#onlinecount").css("height", $(window).height()-120 );

        $(window).resize(function(){
            $("#onlinecount").css("height", $(window).height()-120 );
        });
    });
    //    var socket=io.connect("http://192.168.1.105:8888");
var socket=io.connect("http://localhost:8888");
    //链接服务端
    socket.on("server",function(evt){
        var obj = eval(evt.data);
        var code=obj[0]["code"];
        if(code!=1){
            alert("链接服务器失败，请重新登录!")
            location.href="index/index";
        }else{
            $("#countUser").html(evt.userCount);
            var arr=evt.onlineUserCount;
            var fir=document.getElementById("fir");
            for(var i=0;i<arr.length;i++){
                var p= document.createElement("p");
                p.innerHTML=arr[i];
                fir.appendChild(p);
            }
            layer_login();
        }
    })
    //接收消息
    socket.on("message",function(evt){
        var time=(new Date()).toLocaleString();
        var ohtml= document.getElementById("onlinecount");
        var ospan=document.createElement("a");
        ospan.innerHTML=time;
        var para = document.createElement("h2");

//        var h=""+evt.name+": "+evt.msg;
//        para.className="pleft";
//        para.innerHTML=h;
        ohtml.appendChild(ospan);
        var str='<div> ';
          str =str ='<div style="float: left"><img style="height: 35px;width: 35px;" src="/images/top.png"></div>'
         str = str + '<div class="send" style="width:auto;min-width: 30px;">'+evt.msg+'</div>';
         str=  str + '</div>';
        $("#onlinecount").append(str);
    })
    //发送信息
    function submit(){
        var msg=$("#content").val();//内容
        if(msg==""||msg==undefined||msg==null){
           return layer.msg("请输入要发送的内容！");
        }
        var name=$("#Send").val();//发送消息的人
        data={"msg":msg,"name":name}
        $("#content").val("");
        socket.emit("message",data);
    }
    //登录
    function userlogin(){
        var username = $("#username").val();
      var password = $("#password").val();
      if(username==''||username==undefined||username==null){
        alert("请输入账号");
        return;
      }
      if(password==null||password==undefined||password==''){
        alert("请输入密码");
        return;
      }

      var data = {"name":username,"pwd":password};
        $("#Send").val(username);
      socket.emit("login",data);
      socket.on("login",function(evt){
        if(evt.code==10){
            layer.closeAll();
            var arr=evt.onlineUserCount;
            //好友总数
            $("#countUser").html(evt.userCount);
            //在线好友
            $("#fir").html("");//清空在线好友
            var fir=document.getElementById("fir");
            for(var i=0;i<arr.length;i++){
                var p= document.createElement("p");
                p.innerHTML=arr[i];
                fir.appendChild(p);
            }
            //进去聊天室
            var allmsg=document.getElementById("onlinecount");
            var b = document.createElement("h1");
            var c= document.createTextNode("欢迎"+evt.data.username+"进入聊天室");
            b.appendChild(c);
            allmsg.appendChild(b)
        }else{
           layer.alert("账号或者密码错误");
        }
      })
    }
    //错误
    socket.on("error",function(evt){
        if(evt.code==11){
            layer.alert("请先登录！");
            setTimeout(function(){
                layer_login();
            },1000)

        }
    })
    //登录框
    function layer_login(){
        //页面层
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['820px', '440px'], //宽高
            content: $("#login"),
        });
    }
    //退出
    function exit(){
        var name=$("#Send").val();
        data={"name":name};
        socket.emit("exit",data);
    }
    socket.on("exit",function(evt){
        var name=$("#Send").val();
        if(name==evt.name){
            location.href="/index";
        }else
        {
            //退出通知
            var allmsg=document.getElementById("onlinecount");
            var b = document.createElement("h1");
            var c= document.createTextNode(""+evt.name+"退出聊天室");
            b.appendChild(c);
            allmsg.appendChild(b)
            //更新在线人数
            $("#countUser").html(evt.userCount);
            //在线好友
            var arr=evt.onlineUserCount;
            $("#fir").html("");
            var fir=document.getElementById("fir");
            for(var i=0;i<arr.length;i++){
                var p= document.createElement("p");
                p.innerHTML=arr[i];
                fir.appendChild(p);
            }
        }
    })
</script>
</body>
</html>